/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.codefactory.geneticalgorithm.view;

import com.codefactory.geneticalgorithm.HibernateUtil;
import com.codefactory.geneticalgorithm.MachineInfo;
import com.codefactory.geneticalgorithm.optimizer.GeneticOptimizer;
import com.codefactory.geneticalgorithm.optimizer.Optimizer;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.AbstractTableModel;
import org.hibernate.Session;

/**
 *
 * @author kurbatov
 */
public class RepairSheetJFrame extends javax.swing.JFrame {

    /**
     * Creates new form RepairSheetJFrame
     */
    public RepairSheetJFrame() {
        initComponents();
        tableModel = new MachinesListTableModel();
        tableModel.setData(new ArrayList<MachineInfo>());
        machineListTable.setModel(tableModel);
        
        scheduleTableModel = new RepairScheduleTableModel();
        scheduleTable.setModel(scheduleTableModel);
        
        refresh();
    }

    public void refresh(){
        Session s = HibernateUtil.getSessionFactory().openSession();
        List<MachineInfo> data = (List<MachineInfo>)s.createCriteria(MachineInfo.class).list();
        s.close();
        tableModel.setData(data);
        optimizer = new GeneticOptimizer(data);
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        closeButton = new javax.swing.JButton();
        optimizationLabel = new javax.swing.JLabel();
        optimizationSpinner = new javax.swing.JSpinner();
        optimizationButton = new javax.swing.JButton();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        machineListTable = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        scheduleTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        closeButton.setText("Закрыть");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        optimizationLabel.setText("итераций");

        optimizationSpinner.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));

        optimizationButton.setText("Оптимизировать");
        optimizationButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                optimizationButtonActionPerformed(evt);
            }
        });

        jSplitPane1.setDividerLocation(230);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Список машин"));

        machineListTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(machineListTable);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 586, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 206, Short.MAX_VALUE)
        );

        jSplitPane1.setLeftComponent(jPanel1);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("План ремонтных работ"));

        scheduleTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(scheduleTable);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 586, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 328, Short.MAX_VALUE)
        );

        jSplitPane1.setRightComponent(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(optimizationButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(optimizationSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(optimizationLabel)
                .addGap(18, 18, 18)
                .addComponent(closeButton)
                .addContainerGap())
            .addComponent(jSplitPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jSplitPane1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(closeButton)
                    .addComponent(optimizationLabel)
                    .addComponent(optimizationSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(optimizationButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void optimizationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_optimizationButtonActionPerformed
        try {
            optimizationSpinner.commitEdit();
        } catch (ParseException ex) {
            Logger.getLogger(RepairSheetJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        int iterations = ((Number)optimizationSpinner.getValue()).intValue();
        for(int i = 0; i < iterations; i++){
            optimizer.optimize();
        }
        scheduleTableModel.setData(optimizer.getSchedule());
    }//GEN-LAST:event_optimizationButtonActionPerformed

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_closeButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closeButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTable machineListTable;
    private javax.swing.JButton optimizationButton;
    private javax.swing.JLabel optimizationLabel;
    private javax.swing.JSpinner optimizationSpinner;
    private javax.swing.JTable scheduleTable;
    // End of variables declaration//GEN-END:variables

    private MachinesListTableModel tableModel;
    private RepairScheduleTableModel scheduleTableModel;
    private Optimizer optimizer;
    
    private static class MachinesListTableModel extends AbstractTableModel{

        private static String[] COLUMN_NAMES = new String[]
            {"Наименование", "Стоимость кап. ремонта", "Время кап. ремонта", "Трудоёмкость кап. ремонта",
             "Стоимость тек. ремонта", "Время тек. ремонта", "Трудоёмкость тек. ремонта"};
        
        private List<MachineInfo> data;
        
        public int getRowCount() {
            return data.size();
        }

        public int getColumnCount() {
            return COLUMN_NAMES.length;
        }

        @Override
        public String getColumnName(int column) {
            return COLUMN_NAMES[column];
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            MachineInfo target = data.get(rowIndex);
            switch(columnIndex){
                case 0: return target.getName();
                case 1: return target.getRepairCosts();
                case 2: return target.getRepairTime();
                case 3: return target.getWorkerCount();
                case 4: return target.getMaintenanceCosts();
                case 5: return target.getMaintenanceTime();
                case 6: return target.getMaintenanceWorkerCount();
            }
            return null;
        }

        public List<MachineInfo> getData() {
            return data;
        }

        public void setData(List<MachineInfo> data) {
            this.data = data;
            fireTableDataChanged();
        }
        
    }

}
